<?php

namespace app\frontend\controller;

use app\common\model\ProductCategory;
use app\frontend\library\DataController;
use Exception;
use think\exception\ValidateException;

class Product extends DataController
{
    protected $mdl = ProductCategory::class;

    protected $defaultPageSize = 100;

    protected $maxPageSize = 1000;

    protected $excludeMainFields = ['aid', 'status', 'is_deleted', 'deleted_at', 'created_at', 'updated_at'];

    protected $allowSortFields = [
        'id',
        'Product.id',
        'Product.price'
    ];

    protected $allowSearchFields = [
        'id',
        'img_url',
        'category_name',
        'Product.id',
        'Product.product_name',
        'Product.format',
        'Product.pic_url',
        'Product.cate_id',
        'Product.status',
        'Product.is_deleted',
    ];

    protected $relations = [
        'Product' => [
            'type' => 'with',
            'model' => \app\common\model\Product::class,
            'fields' => ['id', 'product_name', 'pic_url', 'format', 'remark', 'cate_id', 'price', 'amount', 'proxy', 'flag', 'sex', 'description']
        ]
    ];

    public function getList()
    {
        try{
            //参数验证
            $params = $this->validateParams();

            //模型验证
            if(!$this->mdl) {
                throw new Exception('模型类未定义');
            }

            $query = (new $this->mdl)->newQuery();

            $result = $query->field(['id', 'category_name', 'img_url'])->where(['status' => 1, 'is_deleted' => 0])
                ->with(['Product' => function($q) use($params) {
                    $fields = ['id', 'product_name', 'pic_url', 'format', 'remark', 'cate_id', 'price', 'amount', 'proxy', 'flag', 'sex', 'description'];
                    $q->field($fields);

                    if(!empty($params['sortRules'])) {
                        foreach ($params['sortRules'] as $item) {
                            if(!empty($item['field']) && 'Product.id' == $item['field']) {
                                $q->order(['id' => $item['order']]);
                            }
                        }
                    }

                    $q->where(['status' => 1, 'is_deleted' => 0]);
                }])->paginate([
                'page' => $params['page'],
                'list_rows' => $params['size'],
                'query' => $this->request->get()
            ]);

            $items = $result->items();
            $this->_printDataHook($items);

            return $this->jsonSuccess('success', [
                'list' => $items,
                'pagination' => [
                    'total' => $result->total(),
                    'current_page' => $result->currentPage(),
                    'per_page' => $result->listRows(),
                    'last_page' => $result->lastPage()
                ]
            ]);

        }catch (ValidateException $e){
            return $this->jsonError($e->getError());
        }catch (Exception $e){
            return $this->jsonError($e->getMessage());
        }
    }

    protected function _printDataHook(&$items)
    {
        $url = env('url.frontend_url');

        foreach ($items as $item) {
            if(!in_array('img_url', $this->excludeMainFields) && !empty($item->img_url)) {
                $item->img_url = buildFullUrl($url, 'storage/'. $item->img_url);
            }

            foreach ($item->getData() as $field => $value) {
                if(in_array($field, $this->excludeMainFields)) {
                    unset($item[$field]);
                }
            }

            if(!empty($item->Product)) {
                foreach ($item->Product as $product) {
                    if(!empty($product->pic_url)) {
                        $product->pic_url = buildFullUrl($url, 'storage/'. $product->pic_url);
                    }
                }
            }
        }
    }
}